package com.qzuser.sendmessagebasic.server.dao;

import com.qzuser.sendmessagebasic.common.exception.DataBaseException;
import com.qzuser.sendmessagebasic.common.exception.MessageFileException;
import com.qzuser.sendmessagebasic.common.exception.ToolException;
import com.qzuser.sendmessagebasic.server.binding.Binding;
import com.qzuser.sendmessagebasic.server.exchange.Exchange;
import com.qzuser.sendmessagebasic.server.message.Message;
import com.qzuser.sendmessagebasic.server.queue.Queue;

import java.util.LinkedList;
import java.util.List;

public class DiskCenter {
    private DataBase dataBase;
    private MessageFile messageFile;

    public void init() throws DataBaseException {
        dataBase = new DataBase();
        messageFile = new MessageFile();
        dataBase.init();
        messageFile.init();
    }

    public void insertExchange(Exchange exchange) {
        dataBase.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName) {
        dataBase.deleteExchange(exchangeName);
    }

    public List<Exchange> getExchanges() {
        return dataBase.getExchanges();
    }

    public void insertQueue(Queue queue) throws MessageFileException {
        dataBase.insertQueue(queue);
        messageFile.createFiles(queue.getName());
    }

    public void deleteQueue(String queueName) throws MessageFileException {
        dataBase.deleteQueue(queueName);
        messageFile.deleteFiles(queueName);
    }

    public List<Queue> getQueues() {
        return dataBase.getQueues();
    }

    public void insertBinding(Binding binding) {
        dataBase.insertBinding(binding);
    }

    public void deleteBinding(Binding binding) {
        dataBase.deleteBinding(binding);
    }

    public List<Binding> getBindings() {
        return dataBase.getBindings();
    }

    public void sendMessage(Queue queue, Message message) throws MessageFileException, ToolException {
        messageFile.sendMessage(queue, message);
    }

    public void deleteMessage(Queue queue, Message message, MemoryCenter memoryCenter) throws MessageFileException {
        messageFile.deleteMessage(queue, message);
        if (messageFile.checkGc(queue.getName())) {
            messageFile.gc(queue, memoryCenter);
        }
    }

    public LinkedList<Message> loadMessages(String queueName) throws MessageFileException {
        return messageFile.loadOldFile(queueName);
    }
}
